// directives/throttle.ts
import { Directive, DirectiveBinding } from "vue";

interface ThrottleBinding extends DirectiveBinding {
  value: (...args: any[]) => void;
  arg?: string;
  modifiers: {
    trailing?: boolean;
  };
}
interface ThrottleElement extends HTMLElement {
  _throttledFn?: (...args: any[]) => void;
}
const throttle: Directive = {
  mounted(el: ThrottleElement, binding: ThrottleBinding) {
    const { value, arg, modifiers } = binding;
    let delay = 500; // 默认延迟时间

    if (arg) {
      delay = parseInt(arg);
      if (isNaN(delay)) {
        delay = 500;
      }
    }

    // 确保绑定值是函数
    if (typeof value !== "function") {
      throw new Error("v-throttle directive value must be a function");
    }

    let canRun = true;
    const trailing = modifiers.trailing;

    const throttledFn = (...args: any[]) => {
      if (!canRun) return;

      canRun = false;
      if (!trailing) {
        value(...args);
      }

      setTimeout(() => {
        if (trailing) {
          value(...args);
        }
        canRun = true;
      }, delay);
    };

    el._throttledFn = throttledFn;
    el.addEventListener("click", throttledFn);
  },

  beforeUnmount(el: HTMLElement & { _throttledFn?: (...args: any[]) => void }) {
    if (el._throttledFn) {
      el.removeEventListener("click", el._throttledFn);
    }
  },
};

export default throttle;
